package com.ljy.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ljy.constant.MessageConstant;
import com.ljy.context.BaseContext;
import com.ljy.dto.UserLoginDTO;
import com.ljy.entity.User;
import com.ljy.exception.LoginFailedException;
import com.ljy.mapper.UserMapper;
import com.ljy.properties.WeChatProperties;
import com.ljy.service.UserService;
import com.ljy.utills.HttpClientUtil;
import com.ljy.utills.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;
    static final String wechatLoginURL="https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //调用微信登录接口获取openid和session
        String openid = getOpenid(userLoginDTO);
        //如果获取异常
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //user表中判断是否为新用户,是新用户就自动完成注册
        User user = userMapper.getByOpenid(openid);
        if(user==null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回用户对象
        return user;
    }

    @Override
    public User getUser() {
        Integer id = BaseContext.getCurrentId();
        return userMapper.getById(id);
    }

    @Override
    public void editUser(User user) {
        Integer id = BaseContext.getCurrentId();
        user.setId(id);
        userMapper.editUser(user);
    }

    /**
     * 调用微信接口服务，获取openid
     * @param userLoginDTO
     * @return
     */
    private String getOpenid(UserLoginDTO userLoginDTO) {
        Map<String,String> param=new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code", userLoginDTO.getCode());
        param.put("grant_type","authorization_code");
        String result = HttpClientUtil.doGet(wechatLoginURL, param);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
